package org.example.everyday;

import com.sun.org.apache.bcel.internal.generic.ANEWARRAY;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

public class Lc275 {
    public static void main(String[] args) {
        Lc275 lc275 = new Lc275();

        int n = 6;
        int[][] edges = {{3,0},{3,1},{3,2},{3,4},{5,4}};
        List<Integer> res = lc275.findMinHeightTrees(n,edges);
        for(Integer i : res){
            System.out.println(i);
        }
    }

    public List<Integer> findMinHeightTrees(int n, int[][] edges) {
        List<Integer> res = new ArrayList<>();
        //如果只有一个节点，那么他就是最小高度树
        if(n == 1){
            res.add(0);
            return res;
        }
        //建立各个节点的出度表
        int[] degreee = new int[n];
        //建立图关系
        List<List<Integer>> map = new ArrayList<>();
        for(int i = 0; i < n; i++){
            map.add(new ArrayList<>());
        }
        for(int[] edge : edges){
            degreee[edge[0]]++;
            degreee[edge[1]]++;
            map.get(edge[0]).add(edge[1]);
            map.get(edge[1]).add(edge[0]);
        }
        //建立队列
        Queue<Integer> queue = new LinkedList<>();
        //把所有出度为1的节点，也就是叶子节点入队
        for(int i = 0; i < n; i++){
            if(degreee[i] == 1){
                queue.offer(i);
            }
        }
        while (!queue.isEmpty()){
            res = new ArrayList<>();
            int size = queue.size();
            for(int i = 0; i < size; i++){
                int cur = queue.poll();
                res.add(cur);
                List<Integer> neighbors = map.get(cur);
                for(int neighbor : neighbors){
                    degreee[neighbor]--;
                    if(degreee[neighbor] == 1){
                        queue.offer(neighbor);
                    }
                }
            }
        }
        return res;
    }
}
